package org.jeecg.modules.house.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.house.entity.BisHouse;
import org.jeecg.modules.house.model.BisHouseVo;
import org.jeecg.modules.house.service.IBisHouseService;
import org.jeecg.modules.shiro.authc.util.JwtUtil;
import org.jeecg.modules.system.entity.SysFile;
import org.jeecg.modules.system.service.ISysFileService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Title: Controller
 * @Description: 房源实体
 * @author： jeecg-boot
 * @date： 2019-04-20
 * @version： V1.0
 */
@RestController
@RequestMapping("/bis/house")
@Slf4j
@Api(tags = "房源信息控制器")
public class BisHouseController {
    @Autowired
    private IBisHouseService bisHouseService;

    @Autowired
    private ISysFileService iSysFileService;

    /**
     * 分页列表查询
     *
     * @param bisHouse
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation(value = "获取房源数据列表", notes = "获取房源数据列表", produces = "application/json")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, defaultValue = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, defaultValue = "10", paramType = "query"),
            @ApiImplicitParam(name = "bisHouse", value = "查询条件封装", required = false, paramType = "query")
    })
    public Result<IPage<BisHouse>> queryPageList(BisHouse bisHouse,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        Result<IPage<BisHouse>> result       = new Result<IPage<BisHouse>>();
        QueryWrapper<BisHouse>  queryWrapper = QueryGenerator.initQueryWrapper(bisHouse, req.getParameterMap());
        Page<BisHouse>          page         = new Page<BisHouse>(pageNo, pageSize);
        IPage<BisHouse>         pageList     = bisHouseService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param bisHouseVo
     * @return
     */
    @PostMapping(value = "/add")
    public Result<BisHouse> add(@RequestBody BisHouseVo bisHouseVo, HttpServletRequest request) {
        Result<BisHouse> result = new Result<BisHouse>();
        try {
            String userName = JwtUtil.getUserNameByToken(request);
            bisHouseVo.getBisHouse().setCreateBy(userName);
            bisHouseVo.getBisHouse().setCreateTime(new Date());
            bisHouseService.saveNewBisHouse(bisHouseVo);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param bisHouseVo
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<BisHouse> edit(@RequestBody BisHouseVo bisHouseVo) {
        Result<BisHouse> result = new Result<BisHouse>();
        try {
            bisHouseService.modifyBisHouse(bisHouseVo);
            result.success("操作成功！");
        } catch (Exception e) {
            result.error500("操作失败");
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<BisHouse> delete(@RequestParam(name = "id", required = true) String id) {
        Result<BisHouse> result   = new Result<BisHouse>();
        BisHouse         bisHouse = bisHouseService.getById(id);
        if (bisHouse == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = bisHouseService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<BisHouse> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<BisHouse> result = new Result<BisHouse>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.bisHouseService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "查询房源信息详情", notes = "查询房源信息详情", produces = "application/json")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "房源信息id", required = true, paramType = "query")
    })
    public Result<Object> queryById(
            @RequestParam(name = "id", required = true) String id) {
        Result<Object> result   = new Result<Object>();
        BisHouse       bisHouse = bisHouseService.getById(id);
        if (bisHouse == null) {
            result.error500("未找到对应实体");
        } else {
            LambdaQueryWrapper<SysFile> query = new LambdaQueryWrapper<SysFile>();
            query.eq(SysFile::getProductId, id);
            query.eq(SysFile::getType, CommonConstant.HOUSE_COVER);
            SysFile cover = iSysFileService.getOne(query);

            query = new LambdaQueryWrapper<SysFile>();
            query.eq(SysFile::getProductId, id);
            query.eq(SysFile::getType, CommonConstant.HOUSE_SLIDE);
            List<SysFile> slides = iSysFileService.list(query);

            Map<String, Object> data = new HashMap<>();
            data.put("bisHouse", bisHouse);
            data.put("cover", cover);
            data.put("slides", slides);

            result.setResult(data);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<BisHouse> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String   deString = URLDecoder.decode(paramsStr, "UTF-8");
                BisHouse bisHouse = JSON.parseObject(deString, BisHouse.class);
                queryWrapper = QueryGenerator.initQueryWrapper(bisHouse, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView   mv       = new ModelAndView(new JeecgEntityExcelView());
        List<BisHouse> pageList = bisHouseService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "房源实体列表");
        mv.addObject(NormalExcelConstants.CLASS, BisHouse.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("房源实体列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile>  fileMap          = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file   = entity.getValue();// 获取上传文件对象
            ImportParams  params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BisHouse> listBisHouses = ExcelImportUtil.importExcel(file.getInputStream(), BisHouse.class, params);
                for (BisHouse bisHouseExcel : listBisHouses) {
                    bisHouseService.save(bisHouseExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listBisHouses.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
